package com.shanling.shanlingcontroller.persenter;

import android.content.Context;
import android.util.Log;

import com.actions.ibluz.manager.BluzManager;
import com.actions.ibluz.manager.BluzManagerData;
import com.actions.ibluz.ota.updater.OTAUpdater;
import com.actions.ibluz.ota.updater.OnSendOtaDataListener;
import com.actions.ibluz.ota.updater.OnUpdateListener;
import com.actions.ibluz.ota.updater.Update;
import com.actions.ibluz.ota.updater.UpdatePartConfig;
import com.chipsguide.lib.bluetooth.managers.BluetoothDeviceManager;
import com.google.android.exoplayer2.util.NalUnitUtil;
import com.linkplay.lpvr.avslib.LPAVSManager;
import com.linkplay.lpvr.blelib.ota.LPAVSOTAManager;
import com.linkplay.lpvr.lpvrbean.OtaNotifyEntity;
import com.linkplay.lpvr.lpvrcallback.LPAVSOTAManagerCallback;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.CsrUP2OTABean;
import com.shanling.shanlingcontroller.bean.CsrUP4OTABean;
import com.shanling.shanlingcontroller.bean.Us1OTABean;
import com.shanling.shanlingcontroller.http.BuildFactory;
import com.shanling.shanlingcontroller.http.DeviceApi;
import com.shanling.shanlingcontroller.http.HttpConstants;
import com.shanling.shanlingcontroller.http.OTAApi;
import com.shanling.shanlingcontroller.persenter.contract.LoginContract;
import com.shanling.shanlingcontroller.persenter.contract.OTAContract;
import com.shanling.shanlingcontroller.services.csr.UpgradeGaiaManager;
import com.shanling.shanlingcontroller.utils.PreferenceUtil;

import java.io.File;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.observers.DefaultObserver;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import zlc.season.rxdownload2.RxDownload;
import zlc.season.rxdownload2.entity.DownloadStatus;

/**
 * Created by ch1 on 2019/12/20.
 */

public class OTAPersenter extends RxPresenter <OTAContract.View> implements OTAContract.Presenter, LPAVSOTAManagerCallback {
    private RxDownload rxDownload;
    public OTAPersenter(Context context) {
        rxDownload = RxDownload.getInstance(context)
                .defaultSavePath(Constants.LOCAL_FIRMWARE_PATH) //设置默认的下载路径
                .maxThread(3)                     //设置最大线程
                .maxRetryCount(3)                 //设置下载失败重试次数
                .maxDownloadNumber(1);            //Service同时下载数量
    }

    @Override
    public void getLatestversion(int bletype, String version) {
        switch (bletype){
            case 1:
                break;
            case 2:
                getUS1IVersion(version);
                break;
            case 3:
                int type=PreferenceUtil.getInstance(CustomApplication.getInstance()).getBleName().contains("UP2")? 1:2;
                getCsrVersion(type,version);
                break;
        }
    }

    private void getUS1IVersion(String version) {
      Subscription  sub=BuildFactory.getInstance().create(OTAApi.class, HttpConstants.OTA_URL).getUs1Version("slcontrol_pro","us1i_app")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Us1OTABean>() {
                    @Override
                    public void onCompleted() {
                    }
                    @Override
                    public void onError(Throwable e) {
                        if(mView==null){
                            return;
                        }
                        Log.e("weiyu","onError进来了"+e.toString());
                        mView.getLatestversionFaild();
                    }
                    @Override
                    public void onNext(Us1OTABean o) {
                        if(mView==null){
                            return;
                        }
                        Us1OTABean bean= o;
                        List<Us1OTABean.Us1AppBean> ota = bean.getUs1_app();
                        if(ota==null||ota.size()==0){
                            mView.getLatestversionFaild();
                        }else {
                            String latestVersion = ota.get(0).getVersioncode().replace(".","");
                            String currentVersion=version.replace(".","");
                            if (Integer.valueOf(currentVersion)>=Integer.valueOf(latestVersion)) {
                                mView.Islatestversion();
                            } else {
                                mView.getLatestversionSuccess(latestVersion,ota.get(0).getUrl());
                            }
                        }
                    }
                });


        addSubscription(sub);




    }

    private void getCsrVersion(int type,String version) {
        // type 1up2  //type 2 up4
        String para0;
        String para1;
        Subscription sub = null;
        if(type==1){
            para0="up2_pro";
            para1="up2_ota";
            sub=BuildFactory.getInstance().create(OTAApi.class, HttpConstants.OTA_URL).getUP2Version(para0,para1)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<CsrUP2OTABean>() {
                        @Override
                        public void onCompleted() {
                        }
                        @Override
                        public void onError(Throwable e) {
                            if(mView==null){
                                return;
                            }
                            Log.e("weiyu","onError进来了"+e.toString());
                            mView.getLatestversionFaild();
                        }
                        @Override
                        public void onNext(CsrUP2OTABean o) {
                            if(mView==null){
                                return;
                            }
                            CsrUP2OTABean bean= o;
                            List<CsrUP2OTABean.Up2OtaBean> up2_ota = bean.getUp2_ota();
                            if(up2_ota==null||up2_ota.size()==0){
                                mView.getLatestversionFaild();
                            }else {
                                String latestVersion = up2_ota.get(0).getVersioncode().replace(".","");
                                String currentVersion=version.replace(".","");
                                if (Integer.valueOf(currentVersion)>=Integer.valueOf(latestVersion)) {
                                    mView.Islatestversion();
                                } else {
                                    mView.getLatestversionSuccess(latestVersion,up2_ota.get(0).getUrl());
                                }
                            }
                        }
                    });
        }else {
            para0="up4_pro";
            para1= "up4_ota";
            sub=BuildFactory.getInstance().create(OTAApi.class, HttpConstants.OTA_URL).getUP4Version(para0,para1)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<CsrUP4OTABean>() {
                        @Override
                        public void onCompleted() {
                        }
                        @Override
                        public void onError(Throwable e) {
                            if(mView==null){
                                return;
                            }
                            Log.e("weiyu","onError进来了"+e.toString());
                            mView.getLatestversionFaild();
                        }
                        @Override
                        public void onNext(CsrUP4OTABean o) {
                            if(mView==null){
                                return;
                            }
                            CsrUP4OTABean bean= (CsrUP4OTABean) o;
                            List<CsrUP4OTABean.Up4OtaBean> up4_ota = bean.getUp4_ota();
                            if(up4_ota==null||up4_ota.size()==0){
                                mView.getLatestversionFaild();
                            }else {
                                String latestVersion = up4_ota.get(0).getVersioncode().replace(".","");
                                String currentVersion=version.replace(".","");
                                if (Integer.valueOf(currentVersion)>=Integer.valueOf(latestVersion)) {
                                    mView.Islatestversion();
                                } else {
                                    mView.getLatestversionSuccess(up4_ota.get(0).getVersioncode(),up4_ota.get(0).getUrl());
                                }
                            }
                        }
                    });
        }
        addSubscription(sub);
    }
    @Override
    public void download(String url ,String fileName){
        rxDownload.download(url,fileName,Constants.LOCAL_FIRMWARE_PATH)
                .subscribeOn(io.reactivex.schedulers.Schedulers.io())
                .observeOn(io.reactivex.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<DownloadStatus>() {
                    @Override
                    public void onNext(DownloadStatus downloadStatus) {
                        if(mView==null){
                            return;
                        }
                            //DownloadStatus为下载进度
                            String p = downloadStatus.getPercent();
                            String p1 = p.replace("%", "");
                            Double d = (Double.parseDouble(p1))/2;
                             DecimalFormat df = new DecimalFormat("#.00");
                            mView.onDawnload(df.format(d )+"%");
                    }
                    @Override
                    public void onError(Throwable e) {
                        if(mView==null){
                            return;
                        }
                        mView.onDownloadFaild();
                    }

                    @Override
                    public void onComplete() {
                        if(mView==null){
                            return;
                        }
                        mView.onDownloadSuccess();
                    }
                });
    }

    @Override
    public void startCSROTA(UpgradeGaiaManager mUpgradeGaiaManager,File file) {
        if(mUpgradeGaiaManager==null){
            return;
        }
        mUpgradeGaiaManager.startUpgrade(file);
    }

    @Override
    public void startUS1OTA(Context context,String path) {
        BluetoothDeviceManager bluetoothDeviceManager = CustomApplication.getInstance().getBluetoothDeviceManager();
        BluzManager manager = bluetoothDeviceManager.getBluzManager();
        if(manager==null){
            if(mView== null){
                return;
            }
            mView.onOTAFaild();
            return;
        }
        OTAUpdater  mOtaUpdater = new OTAUpdater(context.getApplicationContext(), new OnSendOtaDataListener() {
            @Override
            public void onSend(byte[] bytes) {
                manager.sendCustomData(bytes);
            }
        });
        manager.setOnCustomDataListener(new BluzManagerData.OnCustomDataListener() {
            @Override
            public void onReady(byte[] bytes) {
                if (mOtaUpdater != null){
                    mOtaUpdater.onReceive(bytes);
                }
            }
        });
        InputStream inputStream = null;
        UpdatePartConfig mUpdatePartConfig = null;
        try {
            inputStream = context.getAssets().open("OTA.xml");
            mUpdatePartConfig = new UpdatePartConfig(inputStream);
        } catch (Exception e) {
            if(mView== null){
                return;
            }
            mView.onOTAFaild();

        }
        if(mUpdatePartConfig == null) {
            if(mView== null){
                return;
            }
            mView.onOTAFaild();
            return;
        }
        Update.Builder builder = new Update.Builder();
        builder.addFirmware(path); //设置升级文件的路径
        builder.listener(new OnUpdateListener(){
            @Override
            public void onUpdateProgress(int currentProgress, int maxProgress, int vol3) {
                float progress = currentProgress / ((float) maxProgress);
                if(mView== null){
                    return;
                }
                mView.onProgress(progress*100);
            }

            @Override
            public void onUpdateError(int i) {
                if(mView== null){
                    return;
                }
                mView.onOTAFaild();
            }
            @Override
            public void onUpdateComplete() {
                if(mView== null){
                    return;
                }
                mView.onOTASuccess();
                mOtaUpdater.confirmUpdateAndReboot();
            }
        }); //监听升级状态
        builder.partConfig(mUpdatePartConfig); //设置升级配置
        Update update = builder.build();
        mOtaUpdater.startUpdate(update); //开始升级
    }

    @Override
    public void StartUS1IOTA(Context context, String path) {
        LPAVSOTAManager lpavsotaManager= LPAVSManager.getInstance(context).getBtManager().getLpavsotaManager();
        if(lpavsotaManager==null){
            if(mView== null){
                return;
            }
            mView.onOTAFaild();
        }
        lpavsotaManager.setLPAVSOTAManagerCallback(this);
        lpavsotaManager.startOTA(path);
    }

    @Override
    public void lpavsOTAUpgrading(int i, float v) {
        if(i==LPAVSOTAManager.LPAVSUpgradingProgressState.LP_AVS_UPGRADING_PROGRESS_UPGRADING){
            if(mView== null){
                return;
            }
            mView.onProgress(v*100);
        }
    }
    @Override
    public void lpavsOTAUpgradeSuccess() {
        if(mView== null){
            return;
        }
        mView.onOTASuccess();
    }
    @Override
    public void lpavsOTAUpgradeFailedError(int i) {
        if(mView== null){
            return;
        }
        mView.onOTAFaild();
    }

    @Override
    public void lpavsOTAManagerCanUpgradeNotify(OtaNotifyEntity otaNotifyEntity) {

    }
}
